/******************************************************************************
 * Copyright (c) 2014 - 2016. Danlu.com Co.Ltd. All rights reserved.          *
 ******************************************************************************/

package cn.com.dhc.danlu.widget;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.request.common.GetPicValCodeRequest;
import cn.com.hd.mall.web.webservices.entity.request.common.ValidatePicValCodeRequest;
import cn.com.hd.mall.web.webservices.entity.response.common.GetPicValCodeResponse;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * @author: 吴海洋
 * @author: 李一方
 * @version: 1.0.0
 * @since: 2016-10-01 15:32
 * @mail: wuhaiyang@danlu.com
 * @desc: 封装了 图形验证码 & 短信验证码
 */
public class ValidateCodeLayout extends LinearLayout {
    private EditText mEtInputGraphicsCode;
    private ImageView mIvGraphics;
    private EditText mEtInputSmsCode;
    private CountTimerButton mCtbCountDown;

    private OnTriggerGetSmsCode mListener;
    private CompositeSubscription mSubscriptionManager;
    private boolean isValidatePicSuc = false;

    public ValidateCodeLayout(Context context) {
        this(context, null);
    }

    public ValidateCodeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ValidateCodeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        if (isInEditMode()) {
            return;
        }

        View view = View.inflate(context, R.layout.dl_common_validate, this);
        initView(view);
        bindAction();
        initApi();
        fetchPicValCode(); // 获取图形验证码
    }

    private void initView(View view) {
        mEtInputGraphicsCode = (EditText) view.findViewById(R.id.et_graphicscode);
        mIvGraphics = (ImageView) view.findViewById(R.id.iv_graphics_validation);
        mEtInputSmsCode = (EditText) view.findViewById(R.id.et_input_sms_code);
        mCtbCountDown = (CountTimerButton) view.findViewById(R.id.ctb_countdown);
    }

    private void bindAction() {
        mIvGraphics.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                fetchPicValCode(); // 获取图形验证码
            }
        });
        mCtbCountDown.setInnerClickListener(new CountTimerButton.OnInnerClickListener() {
            @Override
            public void onClick(View view) {
                if (null != mListener) {
                    if (mListener.onGetCode(true)) {
                        //开始校验图形验证码
                        validatePicCode();
                    }
                }
            }

            @Override
            public void onCountFinish() {

            }
        });
    }

    private void initApi() {
        mSubscriptionManager = new CompositeSubscription();
    }

    /**
     * 获取图形验证码的
     */
    private void fetchPicValCode() {
        GetPicValCodeRequest request = new GetPicValCodeRequest();
        request.setToken(agent.getToken());
        Subscription subscribe = agent.getApi().getPicValCode(request).compose(OperatorUtils.<GetPicValCodeResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<GetPicValCodeResponse>(getContext(), R.string.tips_get_pic_code) {
                    @Override
                    protected void onSuccess(GetPicValCodeResponse getPicValCodeResponse) {
                        mIvGraphics.setImageBitmap(CommonUtils.base64ToBitmap(getPicValCodeResponse.getPicValCode()));
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "图形验证码获取失败！" : displayMessage);
                    }
                });

        mSubscriptionManager.add(subscribe);
    }

    /**
     * 校验图形验证码
     */
    private void validatePicCode() {
        if (isValidatePicSuc) {
            // 之前校验成功了  直接通知前台发送短信验证码
            if (null != mListener) {
                mListener.onGetCode(false);
            }
            return;
        }
        String picCode = mEtInputGraphicsCode.getText().toString().trim();
        if (TextUtils.isEmpty(picCode)) {
            ToastUtil.getInstance().show("请输入图形验证码");
            return;
        }
        ValidatePicValCodeRequest request = new ValidatePicValCodeRequest();
        request.setToken(agent.getToken());
        request.setPicValCode(picCode);
        Subscription subscribe = agent.getApi().validatePicValCode(request).compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>(getContext(), R.string.tips_validate_pic_code) {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        if (null != mListener) {
                            mListener.onGetCode(false);
                        }
                        isValidatePicSuc = true;
                        mIvGraphics.setEnabled(false);
                        mEtInputGraphicsCode.setEnabled(false);
                        mEtInputGraphicsCode.setTextColor(getResources().getColor(R.color.color_888888));
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "图形验证码错误" : displayMessage);
                        fetchPicValCode(); // 获取图形验证码
                    }
                });

        mSubscriptionManager.add(subscribe);
    }

    public void setListener(OnTriggerGetSmsCode listener) {
        mListener = listener;
    }

    public String getInputPicCode() {
        return mEtInputGraphicsCode.getText().toString().trim();
    }

    public String getInputSmsCode() {
        return mEtInputSmsCode.getText().toString().trim();
    }

    @Override
    protected void onDetachedFromWindow() {
        if (null != mSubscriptionManager) {
            mSubscriptionManager.unsubscribe();
            mSubscriptionManager = null;
        }
        super.onDetachedFromWindow();
    }

    public void clearAllInput() {
        mEtInputGraphicsCode.getText().clear();
        mEtInputSmsCode.getText().clear();
        fetchPicValCode(); // 获取图形验证码
        changeTimmerStatus(true);
    }

    public void changeTimmerStatus(boolean isClose) {
        if (isClose) {
            mCtbCountDown.stopTimer();
        } else {
            mCtbCountDown.startTimer();
        }
    }

    /**
     * 获取短信验证接口事件触发接口
     */
    public interface OnTriggerGetSmsCode {
        boolean onGetCode(boolean isJudge);
    }
}